import {Card, Col, Radio, Row, Statistic} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {OpOrder} from "@/services/api-functions";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {SYS_ENUMS} from "@/utils/constants";

export interface OrderListProps {
  type: 'RESOURCES' | 'COURSE' | 'SYSTEM' | 'SERVICE' | 'REQUIREMENT',
  title: string,
  queryId?: any,
  designerId?: any,
}

const OrderList: React.FC<OrderListProps> = ({type, queryId, designerId}: OrderListProps) => {
  const [orderStatus, setOrderStatus] = useState<'ALL' | 'PENDING' | 'SUCCESS' | 'CANCEL'>('ALL');
  const [countInfo, setCountInfo] = useState<{ all: number, success: number, pending: number, close: number, doing?: number }>({
    all: 0,
    success: 0,
    pending: 0,
    close: 0,
    doing: 0
  });
  const actionRef = useRef<ActionType>();
  // @ts-ignore
  const [saleInfo, setSaleInfo] = useState<any>(undefined);

  const BASE_COLUMNS: ProColumns[] = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      hideInTable: true,
      fixed: 'left'
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      hideInTable: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInTable: true,
    },
    {
      title: '会员时长(月)',
      dataIndex: 'month',
      hideInTable: true,
      valueType: "digit"
    },
    {
      title: '下单时间',
      dataIndex: 'gmtCreateTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    /*{
      title: '用户名',
      dataIndex: 'nickName',
      hideInTable: true,
    },*/
    {
      title: '订单信息',
      dataIndex: 'orderInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>订单编号：{entity?.id ?? '-'}</p>
        <p>下单时间：{entity?.gmtCreate ?? '-'}</p>
        <p>支付时间：{entity?.paymentTime ?? '-'}</p>
      </div>
    },
    {
      title: '买家信息',
      dataIndex: 'buyerInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>买家昵称：{entity?.buyerUserDto?.nickName ?? '-'}</p>
        <p>联系电话：{entity?.buyerUserDto?.phone ?? '-'}</p>
        {
          entity?.buyerUserDto?.izMembers && <p>会员等级：{entity?.buyerUserDto?.certification ?? '-'}</p>
        }
      </div>
    },
    {
      title: '金额信息',
      dataIndex: 'moneyInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>价格：<span style={{color:'red'}}>{entity?.totalAmount ?? '-'}</span></p>
        {
          type === 'SYSTEM' ? null :  <p>优惠金额：<span style={{color:'red'}}>{entity?.discountAmount ?? '-'}</span></p>
        }
        <p>应付金额：<span style={{color:'red'}}>{entity?.realPayment ?? '-'}</span></p>
      </div>
    },
    {
      title: '支付信息',
      dataIndex: 'payInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>订单状态：{SYS_ENUMS.ORDER_STATUS[entity?.orderStatus]?.text ?? '-'}</p>
        <p>支付方式：{SYS_ENUMS.PAYMENT_TYPE[entity?.paymentChannel]?.text ?? '-'}</p>
      </div>
    },
  ]

  const RESOURCE_COLUMNS: ProColumns[] = [
    {
      title: '资源信息',
      dataIndex: 'resourceInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>资源标题：{entity?.title ?? '-'}</p>
        <p>作者：{entity?.sellerUserDto?.nickName ?? '-'}</p>
      </div>
    },
  ]

  const COURSE_COLUMNS: ProColumns[] = [
    {
      title: '课程信息',
      dataIndex: 'courseInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>课程标题：{entity?.title ?? '-'}</p>
        <p>作者：{entity?.sellerUserDto?.nickName ?? '-'}</p>
        <p>课时数：{entity?.videoNum ?? '-'}</p>
      </div>
    },
  ]

  const SYSTEM_COLUMNS: ProColumns[] = [
    {
      title: '商品信息',
      dataIndex: 'offeringInfo',
      ellipsis: true,
      width: 200,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>商品名称：{entity?.title ?? '-'}</p>
        <p>会员时长：{entity?.month ?? '0'}个月</p>
        {/*<p>会员开始时间：{entity?.startTime}</p>*/}
        {/*<p>会员结束时间：{entity?.endTime}</p>*/}
      </div>
    },
  ]

  useEffect(() => {
    OpOrder.saleInfo(type).then(({code, data}) => {
      if (isSuccess(code)) {
        setSaleInfo(data)
      }
    })


  }, [type])

  const getCurrentColumns = () => {
    if (type === 'RESOURCES') {
      return RESOURCE_COLUMNS
    } else if (type === 'COURSE') {
      return COURSE_COLUMNS
    } else if (type === 'SYSTEM') {
      return SYSTEM_COLUMNS
    }
    return [];
  }

  return (
    <PageContainer>
      <Row gutter={24} style={{marginBottom: 24}}>
        <Col span={3}><Card><Statistic title="今日订单数" value={saleInfo?.todayOrderNum ?? 0}/></Card></Col>
        <Col span={3}><Card><Statistic title="今日交易额" value={saleInfo?.todayTransactionAmount ?? 0}
                                       prefix='￥'/></Card></Col>
        <Col span={3}><Card><Statistic title="本月订单数" value={saleInfo?.monthOrderNum ?? 0}/></Card></Col>
        <Col span={3}><Card><Statistic title="本月交易额" value={saleInfo?.monthTransactionAmount ?? 0}
                                       prefix='￥'/></Card></Col>
        <Col span={3}><Card><Statistic title="本年订单数" value={saleInfo?.yearOrderNum ?? 0}/></Card></Col>
        <Col span={3}><Card><Statistic title="本年交易额" value={saleInfo?.yearTransactionAmount ?? 0}
                                       prefix='￥'/></Card></Col>
        <Col span={3}><Card><Statistic title="订单总数" value={saleInfo?.orderNum ?? 0}/></Card></Col>
        <Col span={3}><Card><Statistic title="订单总交易额" value={saleInfo?.transactionAmount ?? 0} prefix='￥'/></Card></Col>
      </Row>
      <Row gutter={24}>
        <Col span={24}>
          <ProTable<any, any>
            headerTitle={<Radio.Group value={orderStatus} onChange={(e) => {
              setOrderStatus(e.target.value)
              actionRef.current?.reload()
            }}>
              <Radio.Button value='ALL'>全部 {countInfo?.all ?? 0}</Radio.Button>
              <Radio.Button value='PENDING'>待付款 {countInfo?.pending ?? 0}</Radio.Button>
              <Radio.Button value='SUCCESS'>交易完成 {countInfo?.success ?? 0}</Radio.Button>
              <Radio.Button value='CANCEL'>交易取消 {countInfo?.close ?? 0}</Radio.Button>
            </Radio.Group>}
            actionRef={actionRef}
            rowKey="key"
            search={{labelWidth: 120,}}
            request={async (params) => {

              const query = {...params}
              if (orderStatus !== 'ALL') {
                query.orderStatus = orderStatus
              }
              if (params.orderNumber) {
                query.orderNumber = params.orderNumber
              }else{
                if (queryId) {
                  query.orderId = queryId
                }
                if (designerId) {
                  query.designerId = designerId
                }
              }

              if (params.gmtCreateTimeRange) {
                query.startTime = params.gmtCreateTimeRange[0]
                query.endTime = params.gmtCreateTimeRange[1]
                delete query.gmtCreateTimeRange
              }

              const {data: {data, total}, code}: any = type === 'RESOURCES'
                ? await OpOrder.resourcesPageQuery(query)
                : type === 'COURSE'
                  ? await OpOrder.coursePageQuery(query)
                  : type === 'SYSTEM'
                    ? await OpOrder.serverPageQuery(query)
                    : type === 'SERVICE'
                      ? await OpOrder.servicePageQuery(query)
                      : await OpOrder.demandPageQuery(query);

              const res = await OpOrder.countInfo(type);

              if (isSuccess(res.code)) {
                setCountInfo(res.data)
              }

              return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
            }}
            columns={[...BASE_COLUMNS, ...getCurrentColumns()]}
            scroll={{x: 1300}}
          />
        </Col>
      </Row>
    </PageContainer>
  );
};

export default OrderList;
